package com.aiserver.controller;

import com.aiserver.common.Result;
import com.aiserver.dto.LoginRequest;
import com.aiserver.dto.LoginResponse;
import com.aiserver.entity.User;
import com.aiserver.service.AuthService;
import com.aiserver.service.WechatService;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 * 处理登录、注册、验证码等认证相关请求
 */
@RestController
@RequestMapping("/auth")
@Validated
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AuthService authService;

    @Autowired
    private WechatService wechatService;

    /**
     * 用户名密码登录
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@RequestBody(required = false) LoginRequest request, 
                                     HttpServletRequest httpRequest) {
        try {
            LoginRequest loginRequest = request;
            
            // 检查是否有解密数据
            String decryptedData = (String) httpRequest.getAttribute("decryptedData");
            if (decryptedData != null) {
                // 使用解密后的数据
                loginRequest = JSON.parseObject(decryptedData, LoginRequest.class);
                logger.debug("使用解密数据进行登录: {}", decryptedData);
            }
            
            if (loginRequest == null) {
                return Result.error("登录数据不能为空");
            }
            
            // 手动验证必填字段
            if (loginRequest.getUsername() == null || loginRequest.getUsername().trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }
            
            if (loginRequest.getPassword() == null || loginRequest.getPassword().trim().isEmpty()) {
                return Result.error("密码不能为空");
            }
            
            LoginResponse response = authService.login(loginRequest);
            return Result.success("登录成功", response);
        } catch (Exception e) {
            logger.error("登录失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 手机验证码登录
     */
    @PostMapping("/sms-login")
    public Result<LoginResponse> smsLogin(
            @NotBlank(message = "手机号不能为空") @RequestParam String phone,
            @NotBlank(message = "验证码不能为空") @RequestParam String code) {
        try {
            LoginResponse response = authService.smsLogin(phone, code);
            return Result.success("登录成功", response);
        } catch (Exception e) {
            logger.error("短信登录失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 微信登录
     */
    @PostMapping("/wechat-login")
    public Result<LoginResponse> wechatLogin(
            @NotBlank(message = "授权码不能为空") @RequestParam String code,
            @RequestParam(required = false) String state) {
        try {
            LoginResponse response = authService.wechatLogin(code, state);
            return Result.success("登录成功", response);
        } catch (Exception e) {
            logger.error("微信登录失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取微信授权URL
     */
    @GetMapping("/wechat-auth-url")
    public Result<String> getWechatAuthUrl(@RequestParam(required = false) String state) {
        try {
            String authUrl = wechatService.generateAuthUrl(state);
            return Result.success("获取成功", authUrl);
        } catch (Exception e) {
            logger.error("获取微信授权URL失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 微信授权回调
     */
    @GetMapping("/wechat/callback")
    public Result<LoginResponse> wechatCallback(
            @RequestParam String code,
            @RequestParam(required = false) String state) {
        try {
            LoginResponse response = authService.wechatLogin(code, state);
            return Result.success("登录成功", response);
        } catch (Exception e) {
            logger.error("微信授权回调失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 刷新token
     */
    @PostMapping("/refresh-token")
    public Result<LoginResponse> refreshToken(
            @NotBlank(message = "刷新token不能为空") @RequestParam String refreshToken) {
        try {
            LoginResponse response = authService.refreshToken(refreshToken);
            return Result.success("刷新成功", response);
        } catch (Exception e) {
            logger.error("刷新token失败", e);
            return Result.unauthorized(e.getMessage());
        }
    }

    /**
     * 登出
     */
    @PostMapping("/logout")
    public Result<Void> logout(HttpServletRequest request) {
        try {
            String token = extractToken(request);
            if (token != null) {
                authService.logout(token);
            }
            return Result.<Void>success("登出成功", null);
        } catch (Exception e) {
            logger.error("登出失败", e);
            return Result.<Void>error(e.getMessage());
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<User> register(
            @NotBlank(message = "用户名不能为空") @RequestParam String username,
            @NotBlank(message = "密码不能为空") @RequestParam String password,
            @RequestParam(required = false) String phone) {
        try {
            User user = authService.register(username, password, phone);
            // 不返回密码
            user.setPassword(null);
            return Result.success("注册成功", user);
        } catch (Exception e) {
            logger.error("注册失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 发送短信验证码
     */
    @PostMapping("/send-sms-code")
    public Result<Void> sendSmsCode(@NotBlank(message = "手机号不能为空") @RequestParam String phone) {
        try {
            authService.sendSmsCode(phone);
            return Result.<Void>success("验证码发送成功", null);
        } catch (Exception e) {
            logger.error("发送短信验证码失败", e);
            return Result.<Void>error(e.getMessage());
        }
    }

    /**
     * 生成图片验证码
     */
    @GetMapping("/captcha")
    public Result<Map<String, String>> generateCaptcha() {
        try {
            String key = "captcha_" + System.currentTimeMillis();
            String imageBase64 = authService.generateCaptcha(key);
            
            Map<String, String> result = new HashMap<>();
            result.put("key", key);
            result.put("image", imageBase64);
            
            return Result.success("生成成功", result);
        } catch (Exception e) {
            logger.error("生成验证码失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 验证图片验证码
     */
    @PostMapping("/verify-captcha")
    public Result<Boolean> verifyCaptcha(
            @NotBlank(message = "验证码key不能为空") @RequestParam String key,
            @NotBlank(message = "验证码不能为空") @RequestParam String code) {
        try {
            boolean isValid = authService.verifyCaptcha(key, code);
            return Result.success("验证完成", isValid);
        } catch (Exception e) {
            logger.error("验证码验证失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 从请求中提取token
     */
    private String extractToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}